﻿// -----------------------------------------------------------------------
// <copyright file="MultiPartContent.cs" company="Zen Design Corp">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Zen.BlackBerry.Common
{
	using System;
	using System.Collections.Generic;
	using System.IO;

	/// <summary>
	/// Represents multi-part message body content.
	/// </summary>
	public class MultiPartContent : Content
	{
		private IList<Content> _parts;

		/// <summary>
		/// Initializes a new instance of the <see cref="MultiPartContent"/> class.
		/// </summary>
		public MultiPartContent()
			: this(new BoundaryGenerator())
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="MultiPartContent"/> class.
		/// </summary>
		/// <param name="generator">The MIME boundary generator.</param>
		public MultiPartContent(IBoundaryGenerator generator)
		{
			Boundary = generator.MakeBoundary();
			ContentType = string.Format(
				"multipart/related; boundary={0}", Boundary);
		}

		/// <summary>
		/// Gets the MIME boundary.
		/// </summary>
		/// <value>The boundary.</value>
		public string Boundary
		{
			get;
			private set;
		}

		/// <summary>
		/// Gets or sets the parts.
		/// </summary>
		/// <value>The parts.</value>
		public IList<Content> Parts
		{
			get
			{
				if (_parts == null)
				{
					_parts = new List<Content>();
				}
				return _parts;
			}
			set
			{
				_parts = value;
			}
		}

		/// <summary>
		/// Gets a value indicating whether this instance is empty.
		/// </summary>
		/// <value><c>true</c> if this instance is empty; otherwise, <c>false</c>.</value>
		public override bool IsEmpty
		{
			get
			{
				return _parts == null || _parts.Count == 0;
			}
		}

		/// <summary>
		/// Writes this instance to the specified <see cref="StreamWriter"/>.
		/// </summary>
		/// <param name="writer">The writer.</param>
		public override void WriteTo(StreamWriter writer)
		{
			if (IsEmpty)
			{
				throw new InvalidOperationException("MultiPartContent is empty.");
			}

			WriteHeadersTo(writer);
			writer.WriteLine();
			foreach (var part in _parts)
			{
				if (!part.IsEmpty)
				{
					writer.WriteLine("--{0}", Boundary);
					writer.Flush();
					part.WriteTo(writer);
					writer.Flush();
				}
			}
			writer.WriteLine("--{0}--", Boundary);
			writer.Flush();
		}
	}
}
